﻿#include "MyTreeView.h"



MyTreeView::MyTreeView(QWidget* parent)
    : QTreeView(parent)
{
    setAcceptDrops(true);
    setDragDropMode(QAbstractItemView::DragDrop);

    // 初始化删除动作
    deleteAction = new QAction("删除", this);
    deleteAction->setShortcut(QKeySequence::Delete); // 绑定 Delete 键
    connect(deleteAction, &QAction::triggered, this, &MyTreeView::deleteSelected);
    addAction(deleteAction);
}

void MyTreeView::dropEvent(QDropEvent * event)
{
    if (event->mimeData()->hasUrls())
    {
        // 获取顶级目录路径
        QFileSystemModel* fileSystemModel = qobject_cast<QFileSystemModel*>(model());
        if (!fileSystemModel) {
            event->ignore();
            return;
        }
        QString topLevelPath = fileSystemModel->rootPath();
        QDir topLevelDir(topLevelPath);
        QString parentDirPath = topLevelDir.path();

        //
        QModelIndex index = indexAt(event->pos());
        QString targetPath;
        if (!index.isValid()) {
            targetPath = parentDirPath;
        }
        else {
            targetPath = model()->data(index, QFileSystemModel::FilePathRole).toString();
        }


        QList<QUrl> urls = event->mimeData()->urls();
        for (const QUrl& url : urls)
        {
            QString sourcePath = url.toLocalFile();
            QString fileName = QFileInfo(sourcePath).fileName();
            QString destinationPath = QDir(targetPath).filePath(fileName);

            // 移动或复制文件到目标文件夹中
            if (QFile::exists(destinationPath))
            {
                // 如果文件已经存在，可以对话框确认覆盖或跳过
                QMessageBox::StandardButton btn = QMessageBox::question(this, tr("Confirm Overwrite"),
                    tr("The following files already exist:\n%1\nDo you want to overwrite them?").arg(destinationPath),
                    QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
                if (btn == QMessageBox::Yes)
                {
                    QFile::remove(destinationPath);
                    QFile::rename(sourcePath, destinationPath);
                }
                else if (btn == QMessageBox::No)
                {
                    // 用户选择跳过，不做任何操作
                }
                else
                {
                    // 用户选择取消，取消整个拖放操作
                    event->ignore();
                    return;
                }
            }
            else
            {
                QFile::rename(sourcePath, destinationPath);
            }
        }
        event->acceptProposedAction();
    }
    else
    {
        event->ignore();
    }


}

/*
* dragEnterEvent 函数在用户将文件拖动到树视图范围内时被调用
*/
void MyTreeView::dragEnterEvent(QDragEnterEvent* event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
    else {
        event->ignore();
    }
}

/*
* dragMoveEvent 函数在用户在树视图范围内拖动文件时被调用。
*/
void MyTreeView::dragMoveEvent(QDragMoveEvent* event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
    else {
        event->ignore();
    }
}

MyTreeView::~MyTreeView()
{}

void MyTreeView::contextMenuEvent(QContextMenuEvent * event)
{
    QModelIndex index = indexAt(event->pos());
    if (index.isValid()) {
        QMenu menu(this);
        menu.addAction(deleteAction);
        menu.exec(event->globalPos());
    }
}

void MyTreeView::deleteSelected()
{
    QModelIndexList selected = selectionModel()->selectedRows();
    if (selected.isEmpty()) return;

    // 确认对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除", "确定要删除选中的文件/目录吗？",
        QMessageBox::Yes | QMessageBox::No);
    if (reply != QMessageBox::Yes) return;

    // 遍历删除选中的文件或目录
    QFileSystemModel* model = qobject_cast<QFileSystemModel*>(this->model());
    if (!model) return;

    for (const QModelIndex& index : selected) {
        QString path = model->filePath(index);
        QFileInfo fileInfo(path);

        bool success = false;
        if (fileInfo.isDir()) {
            // 删除目录（递归删除）
            success = QDir(path).removeRecursively();
        }
        else {
            // 删除文件
            success = QFile::remove(path);
        }

        // 处理删除失败
        if (!success) {
            QMessageBox::warning(this, "错误", "无法删除: " + path);
        }
    }

    // 强制刷新模型（关键！）
    QString currentRoot = model->rootPath();
    model->setRootPath("");      // 临时清空根路径
    model->setRootPath(currentRoot); // 恢复根路径
}
